<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import io, { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { onMounted, onUnmounted, ref, nextTick, provide } from 'vue'
import { useRoute } from 'vue-router'
import { MsgType, OrderType } from '@/enums'
import type { Message, TimeMessages } from '@/types/room'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { Toast } from 'vant'
import dayjs from 'dayjs'
// 消息列表
const list = ref<Message[]>([])
const store = useUserStore()
const route = useRoute()
const consult = ref<ConsultOrderItem>()
provide('consult', consult)
// 判断是否是第一次接受消息
const initialMsg = ref(true)

let socket: Socket
onUnmounted(() => {
  socket.close()
})
// // 发送消息
const sendText = (text: string) => {
  socket.emit('sendChatMsg', {
    // 发送人id
    from: store.user?.id,
    // 接收人id
    to: consult.value?.docInfo?.id,
    // 消息的类型  文字聊天
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}
// 发送图片
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}
// 下拉刷新
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, consult.value?.id)
}
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)

// 页面挂挂载的时候创建socket请求实例
onMounted(async () => {
  // 建立链接，创建 socket.io 实例
  const socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 使用chatMsgList 接收聊天记录结果  TimeMessages消息分组列表 （默认消息）
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 准备转换常规消息列表
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      arr.push({
        // // 消息类型
        msgType: MsgType.Notify,
        // 聊天内容信息
        msg: { content: item.createTime },
        // 绘话时间
        createTime: item.createTime,
        // 聊天消息id
        id: item.createTime
      })
      // 把item里的items展开添加到数组里面去
      arr.push(...item.items)
    })
    // console.log(arr)
    // 追加到聊天消息列表
    list.value.unshift(...arr)
    //表示加载完成。
    loading.value = false
    if (!data.length) {
      return Toast('没有聊天记录了')
    }
    nextTick(() => {
      //判断是否是第一次加载数据
      if (initialMsg.value) {
        // arr[arr.length - 1].id 是一个数组 arr 中最后一条消息的 id 属性。通过将最新的消息 id 作为参数传递给服务器
        // 修改信息为已读 根据最新的消息id,将之前的消息全部置位已读
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        // 滚动到页面最下方
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false
      }
    })
  })
  // 获取订单详情
  const res = await getConsultOrderDetail(route.query.orderId as string)
  // console.log(res)
  consult.value = res?.data
  // 监听订单的状态
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
  // 接收消息
  // event 是服务器发送的消息，可以查询
  socket.on('receiveChatMsg', async (event) => {
    // 把消息添加到列表里面去进行渲染
    list.value.push(event)
    await nextTick()
    socket.emit('updateMsgStatus', event.id)
    // 用于将页面滚动到垂直方向的最底部位置。
    window.scrollTo(0, document.body.scrollHeight)
  })
  // 如果断开连接后再次连接，需要清空聊天记录
  socket.on('connect', () => {
    list.value = []
  })
})
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <!-- 状态栏 -->
    <room-status :status="consult?.status" :countdown="consult?.countdown"></room-status>
    <!-- 消息 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message v-for="item in list" :item="item" :key="item.id"></room-message>
    </van-pull-refresh>
    <!-- 操作栏 -->
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
